$(document).ready(function () {
	//session 中获取角色，广告主id
	var ctx = $("#ctx").val();
	var role = $("#role").val();
	var advertiserId = $("#sessionadvertiserId").val();


	//定时器每秒调用一次当前时间()
	setInterval(function () {
		var date = new Date();
		$("#today").text(formatDate(date));
	}, 1000);

	if (role == "advertiser") {
		$(".chart-down-left").text("趋势图：" + $("#sessionadvertiserName").val());
	}

	function format(num) {

		if (num == undefined || num == "" || num == null || num == 0) {
			return "0";
		}

		var tempNum = num + "";
		if (tempNum.length <= 3) {
			return num;
		}
		var str = "";
		var decimalPart = "";
		var index = tempNum.indexOf(".");
		if (index == -1) {
			str = tempNum;
		} else {
			str = tempNum.substring(0, index);
			decimalPart = tempNum.substring(index, tempNum.length);
		}
		var newStr = new Array(str.length + parseInt(str.length / 3));
		var strArray = str.split("");
		newStr[newStr.length - 1] = strArray[strArray.length - 1];
		var currentIndex = strArray.length - 1;
		for (var i = newStr.length - 1; i >= 0; i--) {
			if ((newStr.length - i) % 4 == 0) {
				newStr[i] = ",";
			} else {
				newStr[i] = strArray[currentIndex--];
			}
		}
		if (newStr[0] == ",") {
			newStr.shift();
		}
		return newStr.join("") + decimalPart;
	}

	$.post(ctx + '/advertiser/main/dashboard/total', {}, function (data) {
		if (data.result != null) {
			$('#bgsDiv').text(format(parseInt(data.result.impression)));
			$('#djsDiv').text(format(parseInt(data.result.click)));
		}
	});

	$.post(ctx + '/advertiser/main/dashboard/money', {}, function (data) {
		if (data.result != null) {
			$('#balanceSpan').text(format(parseFloat(data.result.balance).toFixed(2)));
			$('#costSpan').text(format(parseFloat(data.result.cost).toFixed(2)));
		}
	});

	$.post(ctx + '/advertiser/main/dashboard/stat', {}, function (res) {
		var pc = 0, mobile = 0;

		res.result.forEach(function (item) {
			pc += item.PC ? item.PC : 0;
			mobile += item.MOBILE ? item.MOBILE : 0;
		});

		$('#traffic-total').text(format(pc + mobile));

		var doughnutData = [{
			value: pc,
			color: 'rgba(0, 162, 92, 1)',
			highlight: 'rgba(0, 162, 92, 0.8)',
			label: 'PC',
			order: 1,
		}, {
			value: mobile,
			color: 'rgba(0, 234, 133, 1)',
			highlight: 'rgba(0, 234, 133, 0.8)',
			label: 'Mobile',
			order: 2,
		}];

		new Chart(document.getElementById('chart-area').getContext('2d')).Doughnut(doughnutData, {
			segmentShowStroke: false,
			percentageInnerCutout: 64,
			responsive: true
		});
	});

	$.loadData = function (no) {
		$.post(ctx + '/advertiser/main/dashboard/listData',
			{
				source: $('#sourceSelect').val(),
				media: $('#mediaText').val()
			},
			function (data) {

				if (data.result != null) {

					var _body = $('#maintable .tbody');
					_body.children().remove();
					var list = data.result;
					var _html = '';
					for (var i = 0; i < list.length; i++) {
						_html += '<tr>';
						_html += '  <td>' + list[i].media + '</td>';
						_html += '  <td>' + format(list[i].request) + '</td>';
						if ($('#hasRight').val() == 'true') {
							_html += '  <td>' + format(list[i].impression) + '</td>';
							_html += '  <td>' + format(list[i].click) + '</td>';
							_html += '  <td>￥' + format(list[i].cost) + '</td>';
						}
						_html += '  <td>' + list[i].syncTimeStr + '</td>';
						_html += '</tr>';
					}

					_body.html(_html);
				}
			});
	};

	$.loadData();

	$('#adxSelect, #sourceSelect').change(function () { $.loadData(); });
	$('#mediaText').keydown(function (e) {
		if (e.keyCode == 13) {
			$.loadData();
		}
	});

	function formatDate(now) {
		var year = fnW(now.getFullYear());
		var month = fnW(now.getMonth() + 1);
		var date = fnW(now.getDate());
		var hour = fnW(now.getHours());
		var minute = fnW(now.getMinutes());
		var second = fnW(now.getSeconds());
		if (hour < 12)
			return year + "年" + month + "月" + date + "日      上午" + hour + ":" + minute + ":" + second;
		else
			return year + "年" + month + "月" + date + "日      下午" + hour + ":" + minute + ":" + second;
	}

	//补位 当某个字段不是两位数时补0
	function fnW(str) {
		var num;
		str >= 10 ? num = str : num = "0" + str;
		return num;
	}

	/*
	*根据时间选择,类型选择,广告主id,查询得到图表
	*	初始化一些数值
	*	
	*/
	var flow = []; flow[0] = []; flow[1] = []; flow[2] = []; flow[3] = [];//图表的纵坐标数据
	var labels = [];//图表的横坐标数据
	var tipLabel = ["Consume", "Impression", "Click", "Rate"];//折线的名字
	var consume = tipLabel[0];
	for (var i = 0; i < 24; i++) {  //默认的X轴的标签labels显示的是昨天的24个小时
		flow[0].push(0);//初始值设置为0;
		flow[1].push(0);//初始值设置为0;
		flow[2].push(0);//初始值设置为0;
		flow[3].push(0);//初始值设置为0;
		if (i < 10) {
			labels.push("0" + i);
		} else {
			labels.push(i);
		}
	}

	/*
	*更改日期的函数，所有更改日期的事件都是调用此函数
	*/
	function cb(start, end) {
		$('#dateRangePicker').val(start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));//将日期显示在input标签里面
		searchAndDraw(start, end);
	}
	/*
	*查询数据和绘制折线图函数, 只要advertiserId和date改变,就调用此函数重新绘制图形
	*	@param 开始日期,结束日期
	*	操作:		更改日期,
	*			调用searchData函数查询数据
	*			调用drawDiagram函数绘制折线图
	*/
	function searchAndDraw(start, end) {
		if (role == 'agent') {
			advertiserId = $('#selectedAdvertiserId3').val();
		}
		var data = flow[0];
		$('#dashboard_chartContent #right_radio input[type="radio"]').each(function () {
			if ($(this).attr("checked") == "checked") {
				var thisval = $(this).val();
				data = flow[thisval];
			}
		});
		drawDiagram(labels, data, consume);//调用绘制图表函数，绘制图表
	}
	/*
	*	默认显示昨天,moment.js是时间日期处理插件,基于jquery
	*/
	cb(moment().subtract(1, 'days'), moment().subtract(1, 'days'));

	/*
	*快速设置为(今天 昨天 过去7天 过去30天)
	*/
	$('#dashboard_chartContent .chart-up .right span.time').click(function (e) { //今天 昨天 过去七天 过去三十天触发函数
		e.preventDefault;
		$('#dashboard_chartContent .chart-up .right span').css('color', '#344c67');
		$(this).css('color', '#36aeea');
		var ind = $(this).index();
		switch (ind) {
			case 0:
				cb(moment(), moment());
				break;
			case 1:
				cb(moment().subtract(1, 'days'), moment().subtract(1, 'days'));
				break;
			case 2:
				cb(moment().subtract(7, 'days'), moment().subtract(1, 'days'));
				break;
			case 3:
				cb(moment().subtract(30, 'days'), moment().subtract(1, 'days'));
				break;
		}
	});

	/*
	*四条折线(消费,曝光数,点击数,点击率),点击切换
	*/
	$('#dashboard_chartContent #right_radio input[type="radio"]').click(function () {
		var n = $(this).val();
		var data = flow[n];
		consume = tipLabel[n];
		var txt = '';
		if (n == 0) { txt = '消费（元）'; }
		if (n == 1) { txt = '曝光数（次）'; }
		if (n == 2) { txt = '点击数（次）'; }
		if (n == 3) { txt = '点击率（%）'; }
		$('#dashboard_chartContent .chart-down .chart-down-right').html(txt);
		drawDiagram(labels, data, consume);
	});

	/*
	*绘制折线图函数
	*	@param 横坐标数值，纵坐标数值，和折线的名字
	*/
	function drawDiagram(labels, data, consume) {
		$('#chart').highcharts({
			chart: { type: 'line' },
			title: { text: '' }, //标题
			//subtitle: { text: 'Source: WorldClimate.com' }, //副标题
			xAxis: { categories: labels },
			yAxis: {
				title: { text: '' },
				plotLines: [{ value: 0, width: 1, color: '#808080' }]
			},
			tooltip: { crosshairs: true, shared: true },
			legend: {
				enabled: false
			},
			credits: {
				enabled: false
			},

			series: [{
				name: consume,
				data: data,
				color: '#36aeea',
				marker: {
					symbol: 'circle',
					fillColor: '#ffffff',
					lineColor: '#36aeea',
					lineWidth: 2,
					radius: 5
				}
			}]
		});
	}

	/*
	*切换折线图和图表
	*/
	$("#diagramHead span:first-child").click(function () {
		$("#sheetContent").css("display", "none");
		$("#diagramHead span:first-child").css("border-bottom", "1px solid #ffffff");
		$("#dashboard_chartContent").css("display", "block");
		$("#diagramHead span:last-child").css("border-bottom", "1px solid #d5dee8");
	});
	$("#diagramHead span:last-child").click(function () {
		$("#dashboard_chartContent").css("display", "none");
		$("#diagramHead span:first-child").css("border-bottom", "1px solid #d5dee8");
		$("#sheetContent").css("display", "block");
		$("#diagramHead span:last-child").css("border-bottom", "1px solid #ffffff");
		var chooseDate = $('#dateRangePicker').val().split(' to ', 2);
		var start = chooseDate[0];//转换为moment格式
		var end = chooseDate[1];//转换为moment格式
		var advertiserId = $('#selectedAdvertiserId3').val();
		var param = {
			'advertiserId': advertiserId,
			'startDate': start,
			'endDate': end
		};
		var _url = ctx + '/advertiser/main/dashboard/list';
		$.post(_url, param, function (data) {
			$('#sheetContent').html(data);
		});
	});

	/*
	*根据广告主id创建订单
	*/
	$('#right button.btn1').click(function () {
		if ($("#isShowRight").val() == "0") {
			var advertiserId = null;
			//判断是广告主还是代理商
			if (role == "advertiser") {
				advertiserId = $("#sessionadvertiserId").val();
			} else {
				advertiserId = $('#selectedAdvertiserId2').val();
			}
			//如果没有选择广告主,弹出提示
			if ((advertiserId == -1) || (advertiserId == null) || (advertiserId == "")) {
				bootbox.alert('请选择广告主');
			} else {
				var _href = $(this).attr('href') + '?advertiserId=' + advertiserId;
				window.location.assign(_href);
			}
		} else {
			bootbox.alert('您没有创建订单的权限！');
		}
	});

	$("ul#advertiser_son_ul2 li").live("click", function () {
		$(this).parents('li').find('span').html($(this).html());
		$("#selectedAdvertiserId2").val($(this).attr("value"));
		$('#advertiser_son_ul2').hide(); //ul隐藏
	});

	//获取广告主的值
	if (role == "agent") {
		$("#advertiser_son_ul").hide();
		$("#advertiser_son_ul2").hide();
		$("#advertiser_son_ul3").hide();
		var _url = ctx + "/widget/selector/provide/advertiser?parentId=" + $("#sessionagentId").val(); //请求地址
		getSelectData("advertiserul_span", "advertiser_son_ul", "advertiserul_box", "全部广告主", _url);
		getSelectData("advertiserul_span2", "advertiser_son_ul2", "advertiserul_box2", "请选择广告主", _url);
		getSelectData("advertiserul_span3", "advertiser_son_ul3", "advertiserul_box3", "请选择广告主", _url);
	} else if (role == "advertiser") {
		$("#advertiserul_span").html($("#sessionadvertiserName").val());
		$("#selectedAdvertiserId").val($("#sessionadvertiserId").val());
		$("#advertiserul_span2").html($("#sessionadvertiserName").val());
		$("#selectedAdvertiserId2").val($("#sessionadvertiserId").val());
		$("#advertiserul_span3").html($("#sessionadvertiserName").val());
		$("#selectedAdvertiserId3").val($("#sessionadvertiserId").val());
	}

	$("ul#advertiser_son_ul li").live("click", function () {
		$(this).parents('li').find('span').html($(this).html());
		$("#selectedAdvertiserId").val($(this).attr("value"));
		$('#advertiser_son_ul').hide(); //ul隐藏
		var agentId = $("#agentId").val(); //获取代理商id
		var advertiserId = $('#selectedAdvertiserId').val();
		var param = {};
		if (advertiserId == -1) {
			param = {
				'agentId': agentId
			};
		} else {
			param = {
				'advertiserId': advertiserId
			};
		}
		//发送ajax请求
		$.ajax({
			type: 'post',	//请求方式，post
			data: param,	//请求参数，param
			url: ctx + '/advertiser/main/dashboard/findCompareAjax',	//请求url
			async: false,	//是否设置为异步请求
			cache: false,	//是否缓存
			dataType: 'json',	//数据类型为json
			success: function (data) { //请求成功回调函数处理，参数为返回回来的json数组
				$('#accountBalance .dataFrame_data').text(data.balance);
				$('#exposure .dataFrame_data').text(data.totalImpression);
				$('#click .dataFrame_data').text(data.totalClick);
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) { //url请求出错的回调函数
				console.info('error');
			}
		});
	});

	$("ul#advertiser_son_ul3 li").live("click", function () {
		$(this).parents('li').find('span').html($(this).html());
		$("#selectedAdvertiserId3").val($(this).attr("value"));
		$('#advertiser_son_ul3').hide(); //ul隐藏
		$('#dashboard_chartContent .chart-down .chart-down-left').html("趋势图：" + $(this).html());
		var chooseDate = $('#dateRangePicker').val().split(' to ', 2);
		var start = moment(chooseDate[0]);//转换为moment格式
		var end = moment(chooseDate[1]);//转换为moment格式
		searchAndDraw(start, end);
	});

	function getSelectData(target_spanId, target_sonulId, target_boxId, defaultName, url) {
		$("#" + target_sonulId).append("<li value='-1' style='width:130px;'>" + defaultName + "</li>");
		$.getJSON(url, function (data) {
			var data_1 = data.advertiserList;
			$.each(data_1, function (key, val) {
				$("#" + target_sonulId).append('<li class="selectop" value=' + val.value + '>' + val.label + '</li>');
			});
		});
		if ($("#isShowRight").val() == "0") {
			$("#" + target_spanId).on("click", function () {
				if (role == "agent") {
					if ($('#' + target_sonulId).height() > 210) {
						$('#' + target_sonulId).addClass("son_ul_change");
                    }
                    $('#' + target_sonulId).show(); //ul显示
				}
			});
		} else {
			if (target_spanId != "advertiserul_span2") {
				$("#" + target_spanId).on("click", function () {
					if (role == "agent") {
						if ($('#' + target_sonulId).height() > 210) {
							$('#' + target_sonulId).addClass("son_ul_change");
                        }
                        $('#' + target_sonulId).show(); //ul显示
					}
				});
			}
		}
		$("#" + target_boxId).mouseleave(function () {
			$('#' + target_sonulId).hide(); //ul隐藏
			$('#' + target_sonulId).removeClass("son_ul_change");
		});
	}
});